package com.psnail.tools;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import org.springframework.web.multipart.MultipartFile;

public class UploadFileTools {

	// 上传用户头像
	public static Map<String, Object> uploadUserPhoto(MultipartFile file, String email, String userResourceAddress) {
		Map<String, Object> result = new HashMap<String, Object>();
		File filePath = new File(userResourceAddress + File.separator + email);
		if (!file.isEmpty()) {
			String fileName = file.getOriginalFilename();// 文件名
			String suffix = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();// 后缀
			if (".png .tif .jpg .jpeg .bmp .gif".contains(suffix)) {
				if (!filePath.exists()) {
					filePath.mkdirs();
				}
				try {
					file.transferTo(new File(filePath.getAbsolutePath() + File.separator + email + suffix));
					result.put("status", 1);
					result.put("message", email + File.separator + email + suffix);
				} catch (Exception e) {
					result.put("status", 0);
					result.put("message", "图片上传异常！");
				}
			} else {
				result.put("status", 0);
				result.put("message", "上传文件不是图片格式！");
			}
		} else {
			result.put("status", 0);
			result.put("message", "未选择图片！");
		}
		return result;
	}

	// 用户上传图片
	public static Map<String, Object> uploadPhoto(MultipartFile file, String email, String userResourceAddress) {
		// 随机id，作为图片名称
		String id = IDTools.createId();
		Map<String, Object> result = new HashMap<String, Object>();
		File filePath = new File(userResourceAddress + File.separator + email);
		if (!file.isEmpty()) {
			String fileName = file.getOriginalFilename();// 文件名
			String suffix = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();// 后缀
			if (".png .tif .jpg .jpeg .bmp .gif".contains(suffix)) {
				if (!filePath.exists()) {
					filePath.mkdirs();
				}
				try {
					file.transferTo(new File(filePath.getAbsolutePath() + File.separator + id + suffix));
					result.put("status", 1);
					result.put("message", email + File.separator + id + suffix);
					result.put("url", email + File.separator + id + suffix);
					result.put("state", "SUCCESS");
				} catch (Exception e) {
					result.put("status", 0);
					result.put("message", "图片上传异常！");
				}
			} else {
				result.put("status", 0);
				result.put("message", "上传文件不是图片格式！");
			}
		} else {
			result.put("status", 0);
			result.put("message", "未选择图片！");
		}
		return result;
	}
}
